package com.raft.framework.ui.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;
import com.raft.framework.R;

import java.util.ArrayList;
import java.util.List;

public abstract class SampleRecyclerViewAdapter<T, VH extends RecyclerView.ViewHolder> extends
    RecyclerView.Adapter<VH> implements
    OnClickListener {


  private List<T> datas = new ArrayList<T>();

  private OnItemClickListener<T> onItemClickListener;

  public void setOnItemClickListener(
      OnItemClickListener<T> onItemClickListener) {
    this.onItemClickListener = onItemClickListener;
  }

  public void setNewData(List<T> list) {
    datas.clear();
    addData(list);
  }

  public void addData(List<T> list) {
    if (list != null) {
      datas.addAll(list);
    }
  }

  public void clearData(){
    datas.clear();
  }

  @Override
  public void onBindViewHolder(@NonNull VH holder, int position) {
    T itemData = getItemData(position);
    holder.itemView.setTag(R.id.item_data, itemData);
    holder.itemView.setTag(R.id.item_position,position);
    if (onItemClickListener != null && itemClickable(position)){
      holder.itemView.setOnClickListener(this);
    }else {
      holder.itemView.setOnClickListener(null);
    }
    onBindViewHolder(holder, position, itemData);
  }


  protected abstract void onBindViewHolder(@NonNull VH holder, int position,T data);


  @Override
  public int getItemCount() {
    return datas.size();
  }

  public List<T> getDatas() {
    return datas;
  }

  public T getItemData(int position){
    if (position < 0 || position >= datas.size()){
      return null;
    }
    return datas.get(position);
  }
  @Override
  public void onClick(View v) {
    if (onItemClickListener != null) {
      Integer pos = (Integer) v.getTag(R.id.item_position);

      if(pos != null && pos >= 0){
        T itemData = getItemData(pos);
        onItemClickListener.onItemClick(v, pos,itemData);
      }

    }

  }


  protected boolean itemClickable(int position){
    return true;
  }

}